<?php
/**
 * Semester Course Setup Controller
 * Semester Course Management
 *
 * semester entry
 *
 * @version $Id: CoursesetupController.php 104 2010-05-10 15:22:30Z yingkuang.chen@gmail.com $
 * @license New BSD License
 * @uses Zend_Controller_Action
 * @package semester
 * @subpackage Controller
 */
class semester_CoursesetupController extends Zend_Controller_Action
{
	function indexAction()
	{
		//學年學期
		if (!$this->_request->getParam('year_semester'))
		$this->view->year_semester = $this->view->Semester['year'].'-'.$this->view->Semester['semester'];
		else
		$this->view->year_semester = $this->_request->getParam('year_semester');

		if (!$this->view->sel_grade = $this->_request->getParam('sel_grade'))
		$this->view->sel_grade = $this->view->lowYear.'-1';  // 預設最低學年

		$bootstrap = $this->getInvokeArg('bootstrap');
		$sfs = $bootstrap->getApplication()->getOption('sfs');
		$this->view->days = $sfs['timetable']['days'];
		$this->view->section = $sfs['timetable']['section'];
		$locale = new Zend_Locale();

		$tdays = $locale->getTranslationList('Days');
		$temp = array_values($tdays['format']['wide']);
		$temp[7] = $temp[0];

		$this->view->tdays = $temp;

		$arr = explode("-",$this->view->year_semester);
		$year = $arr[0];
		$semester = $arr[1];
		$sel_grade = $this->_request->getParam('sel_grade');
		if ($sel_grade) {
			$grade = (int)substr($sel_grade,0,1);
			$class_sn = (int)substr($sel_grade,-1);
		}
		else{
			$grade = $this->view->lowYear;
			$class_sn = 1;
			$sel_grade = sprintf("%d%02d",$grade,$class_sn);
		}
		$semester_section = new Semester_Model_SemesterSection();

		$data = $semester_section->fetchYearSeme($year,$semester,$grade);
		$this->view->data = $data;

		// 排課資料
		$time_table = new Semester_Model_SemesterViewSectionTimetable();
		$this->view->course_arr =  $time_table->getSemesterData($year,$semester,$grade,$class_sn);

	}

	/**
	 * 本學期班級排課統計
	 * @return unknown_type
	 */
	function totalCourseAction()
	{
	    $yearSemester = $this->_request->getParam('year_semester');
	    $semester = new Semester_Model_SemesterClass();
        $this->view->className = $semester->getClassNames($yearSemester);
	    $this->getHelper ( 'layout' )->disableLayout ();
	    $arr = explode("-", $yearSemester);
        $year = $arr[0];
        $semester = $arr[1];
        $q = Doctrine_Query::create()
        ->select('grade, class_sn, COUNT(*) AS cc')
        ->from('Semester_Model_SemesterViewSectionTimetable')
        ->where('year=?', $year)
        ->andwhere('semester=?', $semester)
        ->groupBy('grade, class_sn')
        ->orderBy('grade, class_sn');
        $this->view->data = $q->fetchArray();
	}

	/**
	 * 取出排課資料
	 * @return unknown_type
	 */
	function getcourseAction()
	{
		$this->getHelper ( 'layout' )->disableLayout ();
		$arr = explode("-",$this->_request->getParam('year_semester'));
		$year = $arr[0];
		$semester = $arr[1];
		$selGrade = explode("-",$this->_request->getParam('sel_grade'));
		$grade = (int) $selGrade[0];
		$classSn = (int)$selGrade[1];
		$timeTable = new Semester_Model_SemesterViewSectionTimetable();
		// 已排課程
		$this->view->course_sign_arr = $timeTable->getSemesterSignData($year,$semester,$grade,$classSn);

		//應排課程
		$teacherCourse = new Semester_Model_SemesterTeacherCourse();
		$this->view->teacher_course = $teacherCourse->getClassData($year,$semester,$grade,$classSn);


	}

	/**
	 * TODO 檢查教師在其他班級的課程,避免衝堂
	 * 取出目前任課教師排課情形
	 */
	function teacherCourseAction()
	{
	    $yearSemster = $this->_request->getParam('year_semester');
        $arr = explode("-",$yearSemster);
        $year = (int)$arr[0];
        $semester = (int)$arr[1];
        $grade = (int)substr($this->_request->getParam('sel_class'),0,1);
        $class_sn = (int)substr($this->_request->getParam('sel_class'),1);
        $arr = explode("-", $this->_request->getParam('sel_course'));
        $teacher_sn = $arr[1];
//        echo $year.'--',$semester.'--'.$teacher_sn.'<br>';
        $q = Doctrine_Query::create()
        ->select('grade,class_sn,day,sort,name')
        ->from('Semester_Model_SemesterViewSectionTimetable')
        ->where('year=?', $year)
        ->andWhere('semester=?', $semester)
//        ->andWhere('grade=?',$grade)
//        ->andWhere('class_sn=?', $class_sn)
        ->andWHere('teacher_sn=?', $teacher_sn);
        $res = $q->fetchArray();
//        echo $q->getSqlQuery();
        echo '<pre>';
        print_r($res);exit;
	}

	/**
	 * 新增課程
	 * @return unknown_type
	 */
	function addAction()
	{
		$year_semster = $this->_request->getParam('year_semester');
		$arr = explode("-",$year_semster);
		$year = (int)$arr[0];
		$semester = (int)$arr[1];
		$selClass = explode("-",$this->_request->getParam('sel_class'));
		$grade = (int)$selClass[0];
		$class_sn = (int)$selClass[1];
		$sel_course = explode("-",$this->_request->getParam('sel_course'));
		$subject_sn = $sel_course[0];
		$teacher_sn = $sel_course[1];
		$temp_id = explode("-",$this->_request->getParam('id'));
		$day = $temp_id[1];
		$sort = $temp_id[2];

		$row = Doctrine_Query::create()
		->from("Semester_Model_SemesterSection")
		->where('year=?', $year)
		->andWhere('semester=?', $semester)
		->andWHere('grade=?', $grade)
		->andWHere('sort=?', $sort)
		->fetchOne();
		$section_sn = $row->sn;

		$arr = array();
		$arr['class_sn'] = $class_sn;
		$arr['subject_sn'] = $subject_sn;
		$arr['teacher_sn'] = $teacher_sn;
		$arr['day'] = $day;
		$arr['section_sn'] = $section_sn;

		$timetable = new Semester_Model_SemesterTimetable();
        $timetable->fromArray($arr);
        $timetable->save();

         $sn = $timetable->sn;
        $res = Doctrine_Query::create()
        ->from ('Semester_Model_SemesterViewSectionTimetable')
        ->where('time_sn=?', $sn)
        ->fetchOne(array(),Doctrine_Core::HYDRATE_ARRAY);
		$this->_helper->json($res);

	}

	/**
	 * 刪除課表
	 * @return unknown_type
	 */
	function deleteAction()
	{
		$sn = $this->_request->getParam('sn');
		$sn = (int)substr($sn,3);
		 $res = Doctrine_Query::create()
        ->from ('Semester_Model_SemesterViewSectionTimetable')
        ->where('time_sn=?', $sn)
        ->fetchOne(array(),Doctrine_Core::HYDRATE_ARRAY);

		$id = $res['day'].'-'.$res['sort'];
		$timetable = new Semester_Model_SemesterTimetable();
		$timetable->assignIdentifier($sn);

		$timetable->delete();
		$this->_helper->json($id);
	}

	/**
	 * 下載課表
	 * @return unknown_type
	 */
	function downloadodtAction()
	{
		$yearSemester = $this->_request->getParam('year_semester');
		$semester = new Semester_Model_SemesterClass();
		$className = $semester->getClassNames($yearSemester);

		$selClass = $this->_request->getParam('sel_grade');
		$temp = explode("-",$yearSemester);
		$year = $temp[0];
		$semester = $temp[1];


		$timeTable = new Semester_Model_SemesterViewSectionTimetable();


		$bootstrap = $this->getInvokeArg('bootstrap');
		$sfs = $bootstrap->getApplication()->getOption('sfs');
		$days = $sfs['timetable']['days'];
		$section = $sfs['timetable']['section'];

		$ooPath = realpath(dirname(__FILE__).'/../ooo/coursepaper3');
		//echo $oo_path;

		$ooo = new Sfs_Filesystem_Ooo($ooPath);
		$content = $ooo->getContent('content.xml');
		$content = str_replace("<office:automatic-styles>",
		'<office:automatic-styles><style:style style:name="BREAKPAGE" style:family="paragraph" style:parent-style-name="Standard"><style:paragraph-properties fo:break-before="page"/></style:style>',
		$content);

		$break = '<office:text text:use-soft-page-breaks="true"><text:p text:style-name="BREAKPAGE" /></office:text>';
		$conHeadXml = '<office:body>';
		$conFootXml = '</office:body>';
		$arr1 = explode($conHeadXml,$content);

		$doc_head = $arr1[0].$conHeadXml;
		$arr2 = explode($conFootXml,$arr1[1]);
		$contentBody = $arr2[0];
		$docFoot = $conFootXml.$arr2[1];
		$replaceData = '';
		foreach ($className as $selClass=>$cName) {
		    $tempArr = explode("-", $selClass);
			$grade = (int) $tempArr[0];
			$classSn = (int) $tempArr[1];
			$courseRes = $timeTable->getSemesterData($year,$semester,$grade,$classSn);
			$arr = array();
			for($i=1;$i<=$days;$i++)
			for($j=1;$j<=$section;$j++) {
				$arr['s'.$i.'-'.$j] = '';
				$arr['t'.$i.'-'.$j] = '';
			}
			foreach($courseRes as $res) {
				foreach ($res as $day=>$row) {
					$arr['s'.$day.'-'.$row['sort']] = $row['name'];
					$arr['t'.$day.'-'.$row['sort']] = $row['teacher_name'];
				}
			}
//				print_r($courseRes);exit;
			$arr['school_name']  = $this->view->School['name'];
			$arr['year'] = $year;
			$arr['semester'] = $semester;
			$arr['class_name'] = $cName ;
		//	if ($ii++ > 0 )
		//		$replace_data .= $break;
			$replaceData  .= $ooo->change_temp($arr,$contentBody);
		}
		$replaceData =$doc_head.$replaceData.$docFoot;
		$ooo->add_file($replaceData,'content.xml');
		$ooo->send_odt($yearSemester.'.odt');

	}
}
